package cn.hxzy.common.util;


import cn.hxzy.common.config.OssConfig;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;

import java.io.InputStream;
import java.util.UUID;


public class AliOssUtil {
    public static String uploadFile(String filename, InputStream in) throws Exception {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(OssConfig.ENDPOINT, OssConfig.KEYID, OssConfig.KEYSECRET);
        try {

            //文件名：uuid.扩展名
            filename = UUID.randomUUID().toString().replaceAll("-","") + filename.substring(filename.lastIndexOf("."));

            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("image/jpg");

            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(OssConfig.BUCKETNAME, filename, in,meta);
            // 创建PutObject请求
            ossClient.putObject(putObjectRequest);

            //阿里云文件绝对路径
            String endpoint = OssConfig.ENDPOINT.substring(OssConfig.ENDPOINT.lastIndexOf("//") + 2);
            //返回文件的访问路径
            return "https://" + OssConfig.BUCKETNAME + "." + endpoint + "/" + filename;
        } catch (OSSException oe) {
            throw new RuntimeException(oe.getMessage());
        } catch (ClientException ce) {
            throw new RuntimeException(ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
